<template>
  <div class="app-container" v-loading="loading" style="overflow-x: hidden">
    <el-form
      :model="form"
      ref="formRef"
      :inline="true"
      :rules="rules"
      label-width="130px"
      :disabled="parentType == 'view'"
    >
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="工厂" prop="factoryName">
            <el-tooltip :content="form.factoryName" placement="top">
              <p class="showDetail">{{ form.factoryName }}</p>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工段" prop="workShopName">
            <el-tooltip :content="form.workshopName" placement="top">
              <p class="showDetail">{{ form.workshopName }}</p>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="产线" prop="productLineName">
            <el-tooltip :content="form.productLineName" placement="top">
              <p class="showDetail">{{ form.productLineName }}</p>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="工艺段" prop="sectionName">
            <el-tooltip :content="form.sectionName" placement="top">
              <p class="showDetail">{{ form.sectionName }}</p>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="生产日期" prop="prodDate">
            <el-tooltip :content="form.prodDate" placement="top">
              <p class="showDetail">{{ form.prodDate }}</p>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="班次" prop="classesName">
            <el-tooltip :content="form.classesName" placement="top">
              <p class="showDetail">{{ form.classesName }}</p>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="班组" prop="workGroupName">
            <el-tooltip :content="form.workGroupName" placement="top">
              <p class="showDetail">{{ form.workGroupName }}</p>
            </el-tooltip>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="生产订单" prop=" prodOrderDto " style="width: 100%">
        <el-table :data="prodOrderDto" border style="width: 100%; margin-top: 10px">
          <el-table-column label="订单编号" prop="orderCode" />
          <el-table-column label="产品名称" prop="prodName" />
          <el-table-column label="当班产量" prop="onDutyYield" />
          <el-table-column label="单位" prop="unit" />
        </el-table>
      </el-form-item>
    </el-form>
    <!-- 投料记录 -->
    <div class="previousClasses">
      <div>当前投料</div>
      <el-table :data="prodFeedingVo" border style="width: 100%; margin-top: 10px">
        <el-table-column label="投料内容" prop="matName" />
        <el-table-column label="物料编号" prop="matCode" />
        <el-table-column label="投料批号" prop="feedingBatchNo" />
        <el-table-column label="线边仓" prop="storehouseName" />
        <el-table-column label="库位" prop="binName" />
        <el-table-column label="投入数量" prop="inputQty" />
        <el-table-column label="单位" prop="inputUnit" />
        <el-table-column label="投料时间" prop="feedingTime">
          <template #default="scope">
            <span>{{ scope.row.feedingTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作人" prop="operator" />
        <el-table-column label="记录时间" prop="recordTime">
          <template #default="scope">
            <span>{{ scope.row.recordTime }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 此班次当前投料批号下已报工记录 -->
    <div class="previousClasses">
      <div>此班次当前投料批号下已报工记录</div>
      <el-table :data="YBGList" border style="width: 100%; margin-top: 10px">
        <el-table-column label="产出产品" prop="prodName" />
        <el-table-column label="产出批号" prop="outputBatchNo" />
        <el-table-column label="产出数量" prop="outputQyt" />
        <el-table-column label="有效数量" prop="effectiveQyt" />
        <el-table-column label="损耗" prop="loss" />
        <el-table-column label="缺陷描述" prop="defectDesc" />
        <el-table-column label="单位" prop="inputUnit" />
        <el-table-column label="收卷时间" prop="rollingTime">
          <template #default="scope">
            <span>{{ scope.row.rollingTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="线边仓" prop="storehouseName" />
        <el-table-column label="库位" prop="binName" />
      </el-table>
    </div>
    <!-- 报工 -->
    <div class="previousClasses" v-if="status != '9'">
      <div>
        当前报工
        <span style="margin-left: 15px; font-size: 14px; opacity: 0.6">
          上一产出批号:{{ ['1'].includes(status)? form.preOutputBatchNo4ReportWork: form.preOutputBatchNo }}
        </span>
      </div>
      <el-table
        :data="previousClassInfo"
        :header-cell-class-name="start"
        border
        style="width: 100%; margin-top: 10px"
      >
        <el-table-column min-width="180px" label="产出产品" prop="bomName" />

        <el-table-column min-width="150px" label="产出批号" prop="outputBatchNo">
          <template #default="scope">
            <el-input
              :disabled="!['add', 'reapplyAdd'].includes(parentType)"
              style="width: 100%"
              v-model="scope.row.outputBatchNo"
              controls-position="right"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column min-width="150px" label="产出数量" prop="outputQyt">
          <template #default="scope">
            <el-input-number
              @blur="qtyChange(scope.row)"
              :disabled="!['add', 'reapplyAdd'].includes(parentType)"
              style="width: 100%"
              :min="0.01"
              :precision="2"
              v-model="scope.row.outputQyt"
              controls-position="right"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column min-width="150px" label="有效数量" prop="effectiveQyt">
          <template #default="scope">
            <el-input-number
              @blur="qtyChange(scope.row)"
              :disabled="!['add', 'reapplyAdd'].includes(parentType)"
              style="width: 100%"
              :min="0.01"
              :precision="2"
              v-model="scope.row.effectiveQyt"
              controls-position="right"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="损耗" prop="loss" />
        <el-table-column min-width="180px" label="缺陷描述" prop="defectDesc">
          <template #default="scope">
            <!-- <el-tooltip
              class="box-item"
              effect="dark"
              :content="scope.row.defectDesc"
              placement="top-start"
            > -->
            <el-input
              :disabled="!['add', 'reapplyAdd'].includes(parentType)"
              style="width: 100%"
              v-model="scope.row.defectDesc"
              controls-position="right"
            ></el-input>
            <!-- </el-tooltip> -->
          </template>
        </el-table-column>
        <el-table-column label="单位" prop="unit" />
        <el-table-column label="收卷时间" prop="rollingTime" min-width="200px">
          <template #default="scope">
            <el-date-picker
              :disabled="!['add', 'reapplyAdd'].includes(parentType)"
              v-model="scope.row.rollingTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              :editable="false"
              :clearable="false"
              style="width: 100%"
              type="datetime"
              placeholder="选择投料时间"
            />
          </template>
        </el-table-column>
        <el-table-column label="线边仓" prop="storehouseName" min-width="150px">
          <template #default="scope">
            <el-select
              @change="storehouseCodeChange"
              :disabled="!['add', 'reapplyAdd'].includes(parentType)"
              clearable
              filterable
              v-model="scope.row.storehouseCode"
            >
              <el-option
                v-for="(item, index) in storehouseList"
                :key="index"
                :value="item.storehouseCode"
                :label="item.storehouseName"
              >
                <span>{{ item.storehouseName }}</span>
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="库位" prop="binName" min-width="150px">
          <template #default="scope">
            <!-- <BinSelect
            v-model="scope.row.binCode"
            :key="`bin`"
            :parent="scope.row.storehouseCode"
            @change="binCodeCodeChange"
            placeholder="请选择库位"
          ></BinSelect> -->
            <el-select
              v-model="scope.row.binCode"
              :disabled="!['add', 'reapplyAdd'].includes(parentType)"
              style="width: 100%"
              clearable
              filterable
              @change="binCodeCodeChange"
            >
              <el-option
                v-for="(item, index) in binlist"
                :key="index"
                :label="item.binName"
                :value="item.binCode"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 质检结果 -->
    <div class="previousClasses" v-if="parentType != 'add' && status != '9'">
      <div>质检结果</div>
      <el-table :data="prodQualityTesting" border style="width: 100%; margin-top: 10px">
        <el-table-column label="质检单号" prop="qmsQualityCode" />
        <el-table-column label="质检结果" prop="testingResult">
          <template #default="scope">
            <dict-tag
              v-if="scope.row.testingResult"
              :options="quality_testing_result"
              :value="scope.row.testingResult"
            />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="外观判定" prop="appearanceJudgment" />
        <el-table-column label="性能判定" prop="performanceJudgment" />
        <el-table-column label="不良描述" prop="defectDesc" />
        <el-table-column label="操作人" prop="createBy" />
        <el-table-column label="质检时间" prop="qualityTestingTime" />
      </el-table>
    </div>
    <!-- 此班次当前投料批号下已报工记录 -->
    <div class="previousClasses" v-if="parentType == 'view' && status == '9'">
      <div>退料入仓</div>
      <el-table :data="returnMaterialsList" border style="width: 100%; margin-top: 10px">
        <el-table-column label="入仓单编号" prop="inOrderCode" />
        <el-table-column label="入仓时间" prop="inTime" />
        <el-table-column label="入仓数量" prop="receiveNumber" />
        <el-table-column label="线边仓" prop="storehouseName" />
        <el-table-column label="库位" prop="binName" />
      </el-table>
    </div>
    <div
      class="previousClasses"
      v-if="
        parentType == 'audit' ||
        parentType == 'FQFJ' ||
        (parentType == 'view' && formSH.auditResult)
      "
    >
      <div>报工审核</div>
      <el-form
        :model="formSH"
        ref="formRefSH"
        :inline="true"
        :rules="rulesSH"
        label-width="auto"
        style="width: 100%; margin-top: 20px; margin-left: 20px"
      >
        <el-form-item label="审核结果" prop="auditResult" style="width: 100%">
          <el-radio-group
            :disabled="parentType != 'audit'"
            v-model="formSH.auditResult"
            @change="handleAuditResultChange"
          >
            <el-radio value="1">通过</el-radio>
            <el-radio value="0">不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="审核意见"
          prop="auditOpinion"
          :rules="[
            {
              required: formSH.auditResult == '0',
              message: '请填写审核意见',
              trigger: ['blur', 'change'],
            },
          ]"
        >
          <el-input
            style="width: 600px"
            :disabled="parentType != 'audit'"
            v-model="formSH.auditOpinion"
            :placeholder="parentType == 'view' ? '' : '请填写审核意见'"
            type="textarea"
          />
        </el-form-item>
        <el-form-item
          v-if="parentType == 'view'"
          label="审核时间"
          prop="auditTime"
          style="width: 100%"
        >
          {{ formSH.auditTime }}
        </el-form-item>
      </el-form>
    </div>
    <div class="previousClasses" v-if="parentType == 'FQFJ'">
      <div>分切后批次</div>
      <div
        style="float: right; font-size: 14px; color: blue; cursor: pointer"
        @click="handleAddBatch"
      >
        新增批次
      </div>
      <el-form ref="slittRewindRef" :model="slittRewindList" label-width="0">
        <el-table :data="slittRewindList" border style="width: 100%; margin-top: 10px">
          <el-table-column label="产出产品" prop="bomName" />
          <el-table-column label="产出批号" prop="outputBatchNo">
            <template v-if="editAble" #header>
              <span style="color: red">*</span>
              <span>产出批号</span>
            </template>
            <template v-if="editAble" #default="scope">
              <el-form-item
                label=""
                :prop="`[${scope.$index}].outputBatchNo`"
                :rules="[
                  {
                    required: true,
                    message: '请输入产出批号',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="scope.row.outputBatchNo"
                  @change="handleInputChange($event, scope, 'outputBatchNo')"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="产出数量" prop="outputQyt">
            <template v-if="editAble" #header>
              <span style="color: red">*</span>
              <span>产出数量</span>
            </template>
            <template v-if="editAble" #default="scope">
              <el-form-item
                label=""
                :prop="`[${scope.$index}].outputQyt`"
                :rules="[
                  {
                    required: true,
                    message: '请输入产出数量',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input-number
                  v-model="scope.row.outputQyt"
                  @change="handleInputChange($event, scope, 'outputQyt')"
                  controls-position="right"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="有效数量" prop="effectiveQyt">
            <template v-if="editAble" #header>
              <span style="color: red">*</span>
              <span>有效数量</span>
            </template>
            <template v-if="editAble" #default="scope">
              <el-form-item
                label=""
                :prop="`[${scope.$index}].effectiveQyt`"
                :rules="[
                  {
                    required: true,
                    message: '请输入有效数量',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input-number
                  v-model="scope.row.effectiveQyt"
                  @change="handleInputChange($event, scope, 'effectiveQyt')"
                  controls-position="right"
                  :max="scope.row.outputQyt"
                ></el-input-number>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="损耗" prop="loss" />
          <el-table-column label="缺陷描述" prop="defectDesc">
            <template v-if="editAble" #header>
              <!-- <span style="color: red">*</span> -->
              <span>缺陷描述</span>
            </template>
            <template v-if="editAble" #default="scope">
              <el-form-item
                label=""
                :prop="`[${scope.$index}].defectDesc`"
                :rules="[
                  {
                    required: false,
                    message: '请输入缺陷描述',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-input
                  v-model="scope.row.defectDesc"
                  @change="handleInputChange($event, scope, 'defectDesc')"
                ></el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="单位" prop="unit" />
          <el-table-column label="收卷时间" prop="rollingTime" min-width="200px">
            <template v-if="editAble" #header>
              <span style="color: red">*</span>
              <span>收卷时间</span>
            </template>
            <template v-if="editAble" #default="scope">
              <el-form-item
                label=""
                :prop="`[${scope.$index}].rollingTime`"
                :rules="[
                  {
                    required: true,
                    message: '请选择收卷时间',
                    trigger: 'blur',
                  },
                ]"
              >
                <el-date-picker
                  v-model="scope.row.rollingTime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  :editable="false"
                  :clearable="false"
                  style="width: 100%"
                  type="datetime"
                  placeholder="请选择收卷时间"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="线边仓" prop="storehouseName" width="150">
            <template v-if="editAble" #header>
              <span style="color: red">*</span>
              <span>线边仓</span>
            </template>
            <template v-if="editAble" #default="scope">
              <el-form-item
                label=""
                :prop="`[${scope.$index}].storehouseCode`"
                :rules="[
                  {
                    required: true,
                    message: '请选择线边仓',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <StoreSelect
                  v-model="scope.row.storehouseCode"
                  v-model:name="scope.row.storehouseName"
                  :line="form.lineCode"
                  :section="form.sectionCode"
                  :autoSelect="operationTitle === '确认入仓'"
                  :customOptions="storehouseList"
                  placeholder="请选择线边仓"
                  @change="tableStoreChange($event, scope)"
                ></StoreSelect>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="库位" prop="binName" width="150">
            <template v-if="editAble" #header>
              <span style="color: red">*</span>
              <span>库位</span>
            </template>
            <template v-if="editAble" #default="scope">
              <el-form-item
                label=""
                :prop="`[${scope.$index}].binCode`"
                :rules="[
                  {
                    required: true,
                    message: '请选择库位',
                    trigger: ['blur', 'change'],
                  },
                ]"
              >
                <BinSelect
                  v-model="scope.row.binCode"
                  :key="`bin-${scope.$index}`"
                  :autoSelect="operationTitle === '确认入仓'"
                  :parent="scope.row.storehouseCode"
                  @change="handleInputChange($event, scope, 'binCode')"
                  placeholder="请选择库位"
                ></BinSelect>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                @click="handleSlittRewindDelete(scope.row, scope.$index)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
    <el-dialog
      v-model="dialogVisible"
      title="系统提示"
      width="420"
      append-to-body
      class="custom-dialog"
      draggable
    >
      <p style="color: red">填报的产出数量＞投入数量。</p>
      <p>确定提交报工吗？</p>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="sureSubmit()">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="dialogSlittRewindVisible"
      title="系统提示"
      width="420"
      append-to-body
      class="custom-dialog"
      draggable
    >
      <p style="color: red">填报的产出数量之和＞投入数量。</p>
      <p>确定提交吗？</p>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogSlittRewindVisible = false">取消</el-button>
          <el-button type="primary" @click="slittingData()">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <div v-loading.fullscreen.lock="fullscreenLoading"></div>
  </div>
</template>

<script setup>
import {
  getProdReportWork,
  addDoReportWork,
  againReportWork,
  auditReportWork,
  slittingRewinding,
} from "@/api/productionMgt/productionReport";

import { getFactoryTree } from "@/api/system/dept";
import { listStorehouse } from "@/api/storehouse/storehouse";
import { listStorehouseBin } from "@/api/storehouse/storehouseBin";
import { listProdReportWork, getReturnMaterialsInfo } from "@/api/productionMgt/productionReport";
import { toRefs, ref } from "vue";
import { reactive, useAttrs, getCurrentInstance, onMounted } from "vue";
const attrs = useAttrs();
const { proxy } = getCurrentInstance();
const parentType = ref("add");
const loading = ref(false);
const previousClassInfo = ref([]);
const prodFeedingVo = ref([]);
const prodOrderDto = ref([]);
const prodQualityTesting = ref([]);
const binlist = ref([]);
var factoryOptions = ref([]);

const dialogVisible = ref(false);
const dialogSlittRewindVisible = ref(false);
const submitLoading = ref(false);
const fullscreenLoading = ref(false);
const storehouseList = ref([]);
const status = ref("");
const YBGList = ref([]);
const returnMaterialsList = ref([]);
const slittRewindList = ref([{}]);
const formRefSH = ref();
const editAble = ref(false);
const slittRewindRef = ref("slittRewindRef");
const { quality_testing_result } = proxy.useDict("quality_testing_result");
const emit = defineEmits(["close", "setTitle", "setActions", "setIsActionTop"]);
const start = ({ columnIndex }) => {
  const arr = [1, 2, 3, 7, 8, 9];
  if (arr.includes(columnIndex)) {
    return "start";
  }
};
const actions = ref([
  {
    text: "取 消",
    theme: "",
    handle: () => {
      cancel();
    },
  },
  {
    text: "确 定",
    theme: "primary",
    handle: () => {
      submitForm();
    },
    loading: false,
  },
]);
// const validatedesc = (rule, value, callback) => {
//   if (!value && formSH.value.auditResult === '0') {
//     callback(new Error('请填写审核意见'))
//   }else {
//     callback()
//   }
// }
const data = reactive({
  form: {},
  formSH: {},
  rules: {},
  rulesSH: {
    auditResult: [{ required: true, message: "请选择审核结果", trigger: "change" }],
    // auditOpinion: [{ required: true,validator: validatedesc, trigger: 'blur' }],
  },
});

const { form, rules, formSH, rulesSH } = toRefs(data);

// watch(
//   // factoryOptions,
//   // (val) => {
//   //   if (val && val.length && form.value.id && form.value.sectionCode && form.value.prodDate) {
//   //     getScheduleNames4ChangeShiftsFun()
//   //   }
//   // },
//   // { immediate: true, deep: true }
// )
// 监听选择审核结果变化
function handleAuditResultChange(val) {
  if (val == "1") {
    //清理某个字段的表单验证信息
    formRefSH.value.clearValidate(["auditOpinion"]);
  }
}

function getStorehouseList() {
  listStorehouse({
    factoryCode: form.value.factory,
    workshopCode: form.value.workshopCode,
    lineCode: form.value.productLine,
    // sectionCode: form.value.sectionCode,
    pageNum: 1,
    pageSize: 1000,
  }).then((res) => {
    // 产线下，如果有涂膜工艺段对应的线边仓时，需默认涂膜线边仓及库位数据——>没有的话，不显示任何默认值
    let newArr = JSON.parse(JSON.stringify(res.rows));
    console.log(newArr, "====newArr");
    let firstObj = newArr.find((item) => {
      return item.sectionName == "涂膜工艺段";
    });
    console.log(firstObj, "===firstObj");
    // 因为返回的数组会出现重复的sectionCode，所以不能用sectionCode过滤，
    // 因返回的id是唯一值，所以用Id做判断过滤掉
    let othersArr = newArr.filter((item) => {
      return item.id != firstObj?.id;
    });
    console.log(othersArr, "===");
    if (firstObj) {
      storehouseList.value = [firstObj, ...othersArr];
    } else {
      storehouseList.value = [...othersArr];
    }
    if (!previousClassInfo.value[0].storehouseCode) {
      previousClassInfo.value[0].storehouseCode = storehouseList.value[0].storehouseCode;
      previousClassInfo.value[0].storehouseName = storehouseList.value[0].storehouseName;
      // getListStorehouseBin(previousClassInfo.value[0].storehouseCode)
    }
    getListStorehouseBin(previousClassInfo.value[0].storehouseCode);
  });
}
function getListStorehouseBin(code) {
  if (!code) {
    binlist.value = [];
    return;
  }
  listStorehouseBin({
    storehouseCode: code,
    pageSize: 1000,
    pageNum: 1,
  }).then((res) => {
    binlist.value = res.rows;
    if (!previousClassInfo.value[0].binCode) {
      previousClassInfo.value[0].binCode = binlist.value[0].binCode;
      previousClassInfo.value[0].binName = binlist.value[0].binName;
    }
  });
}
function binCodeCodeChange(value) {
  binlist.value.forEach((item) => {
    if (item.binCode == value) {
      previousClassInfo.value[0].binName = item.binName;
    }
  });
}
function storehouseCodeChange(value) {
  previousClassInfo.value[0].binCode = "";
  previousClassInfo.value[0].binName = "";
  getListStorehouseBin(value);
  storehouseList.value.forEach((item) => {
    if (item.storehouseCode == value) {
      previousClassInfo.value[0].storehouseName = item.storehouseName;
    }
  });
}
function getDetail(id) {
  loading.value = true;
  getProdReportWork(id).then((res) => {
    form.value = res.data;
    previousClassInfo.value = [
      {
        bomName: form.value.bomName,
        outputBatchNo: form.value.outputBatchNo,
        outputQyt: form.value.outputQyt,
        effectiveQyt: form.value.effectiveQyt,
        rollingTime: form.value.rollingTime || proxy.parseTime(new Date()),
        loss: form.value.loss,
        defectDesc: form.value.defectDesc,
        unit: form.value.unit,
        // storehouseCode: form.value.storehouseCode,
        // storehouseName: form.value.storehouseName,
        // binCode: form.value.binCode,
        // binName: form.value.binName,
      },
    ];
    formSH.value = {
      auditTime: form.value.auditTime,
      auditOpinion: form.value.auditOpinion,
      auditResult: form.value.auditResult,
    };
    prodFeedingVo.value = form.value.prodFeedingVo ? [form.value.prodFeedingVo] : [];
    prodOrderDto.value = form.value.prodOrderDto ? [form.value.prodOrderDto] : [];
    prodQualityTesting.value = form.value.prodQualityTesting ? [form.value.prodQualityTesting] : [];
    getStorehouseList();
    loading.value = false;
    // 给分切复卷赋值
    slittRewindList.value = JSON.parse(JSON.stringify(previousClassInfo.value));
    slittRewindList.value[0].outputQyt = "";
    slittRewindList.value[0].effectiveQyt = "";
    slittRewindList.value[0].defectDesc = "";
    // slittRewindList.value[0].outputQyt = previousClassInfo.value[0].rollingTime;
    // slittRewindList.value[0].storehouseCode = previousClassInfo.value[0].storehouseCode;
    // slittRewindList.value[0].storehouseName = previousClassInfo.value[0].storehouseName;
    // slittRewindList.value[0].binCode = previousClassInfo.value[0].binCode;
    // slittRewindList.value[0].binName = previousClassInfo.value[0].binName;
  });
}
// 获取已报工记录
function getYBGList(data) {
  if (data.feedingId) {
    listProdReportWork(
      proxy.addDateRange({
        pageNum: 1,
        pageSize: 10000,
        statusList: "3,4,5,6",
        feedingId: data.feedingId,
        orderByRollingTime: true,
      })
    ).then((response) => {
      if (response.rows && response.rows.length) {
        YBGList.value = response.rows;
      }
    });
  }
}
function qtyChange(row) {
  if (row.effectiveQyt > row.outputQyt) {
    previousClassInfo.value[0].effectiveQyt = row.outputQyt;
  }
  previousClassInfo.value[0].loss = (
    previousClassInfo.value[0].outputQyt - previousClassInfo.value[0].effectiveQyt
  ).toFixed(2);
}
function getFactorys(query) {
  getFactoryTree(query).then((res) => {
    factoryOptions.value = res.data;
  });
}

function cancel() {
  emit("close");
}

function handleInputChange(val, scope, field) {
  // slittRewindList.value[scope.$index][field] = val;
  if (field === "binCode") {
    slittRewindList.value[scope.$index][field] = val.binCode;
    slittRewindList.value[scope.$index].binName = val.binName;
  } else {
    slittRewindList.value[scope.$index][field] = val;
  }
}
function tableStoreChange(val, scope) {
  scope.row.binCode = "";
  slittRewindList.value[scope.$index].storehouseCode = val.storehouseCode;
  slittRewindList.value[scope.$index].storehouseName = val.storehouseName;
}

function handleSlittRewindDelete(row, index) {
  let msg = `是否确认移除所选数据项？`;
  proxy.$modal
    .confirm(msg)
    .then(function () {
      slittRewindList.value.splice(index, 1);
    })
    .then(() => {
      proxy.$modal.msgSuccess("移除成功");
    })
    .catch(() => {});
}
function handleAddBatch() {
  slittRewindList.value.push({
    bomName: slittRewindList.value[0].bomName,
    outputBatchNo: "",
    outputQyt: 0,
    effectiveQyt: 0,
    loss: slittRewindList.value[0].loss,
    defectDesc: "",
    unit: slittRewindList.value[0].unit,
    rollingTime: slittRewindList.value[0].rollingTime,
    storehouseCode: slittRewindList.value[0].storehouseCode,
    storehouseName: slittRewindList.value[0].storehouseName,
    binCode: slittRewindList.value[0].binCode,
    binName: slittRewindList.value[0].binName,
  });
}
function submitForm() {
  if (parentType.value == "FQFJ") {
    submitSlitting();
  } else {
    if (previousClassInfo.value.length) {
      for (let index = 0; index < previousClassInfo.value.length; index++) {
        const element = previousClassInfo.value[index];
        if (!element.outputBatchNo) {
          return proxy.$modal.msgError(`当前报工第${index + 1}行产出批号未填写`);
        }
        if (!element.outputQyt) {
          return proxy.$modal.msgError(`当前报工第${index + 1}行产出数量未填写`);
        }
        if (!element.effectiveQyt) {
          return proxy.$modal.msgError(`当前报工第${index + 1}行有效数量未填写`);
        }
        if (!element.rollingTime) {
          return proxy.$modal.msgError(`当前报工第${index + 1}行收卷时间未选择`);
        }
        if (!element.storehouseCode) {
          return proxy.$modal.msgError(`当前报工第${index + 1}行线边仓未选择`);
        }
        if (!element.binCode) {
          return proxy.$modal.msgError(`当前报工第${index + 1}行库位未选择`);
        }
      }
      // parentType.value == 'audit'
      if (parentType.value == "audit") {
        proxy.$refs["formRefSH"].validate((valid) => {
          if (valid) {
            proxy.$modal
              .confirm("确定提交审核结果吗？")
              .then(function () {
                sureSubmit();
              })
              .catch(() => {});
          }
        });
      } else {
        // 允许产出数量＞投入数量，报工提交时二次确认并提醒，允许提交成功。
        if (form.value.prodFeedingVo.inputQty < previousClassInfo.value[0].outputQyt) {
          dialogVisible.value = true;
        } else {
          proxy.$modal
            .confirm("确定提交报工吗？")
            .then(function () {
              sureSubmit();
            })
            .catch(() => {});
        }
        // proxy.$modal
        //   .confirm('确定提交报工吗？')
        //   .then(function () {
        //     // 允许产出数量＞投入数量，报工提交时二次确认并提醒，允许提交成功。
        //     if (form.value.prodFeedingVo.inputQty < previousClassInfo.value[0].outputQyt) {
        //       dialogVisible.value = true
        //     } else {
        //       sureSubmit()
        //     }
        //   })
        //   .catch(() => {})
      }
    }
  }
}

function submitSlitting() {
  slittRewindRef.value.validate((valid) => {
    if (valid) {
      let nums = null;
      for (let i in slittRewindList.value) {
        nums += slittRewindList.value[i].outputQyt;
      }
      if (nums > prodFeedingVo.value[0].inputQty) {
        dialogSlittRewindVisible.value = true;
      } else {
        slittingData();
      }
    }
  });
}

function slittingData() {
  loading.value = true;
  let obj = { ...form.value };
  obj = Object.assign(obj, previousClassInfo.value[0]);
  obj = Object.assign(obj, formSH.value);
  obj.recordTime = null;
  obj.auditTime = null;
  let params = {};
  params.id = form.value.id;
  params.feedingId = prodFeedingVo.value[0].id;
  params.prodReportWorkList = slittRewindList.value.map((item) => {
    return {
      ...obj,
      params: null,
      ...item,
    };
  });
  slittingRewinding(params).then(() => {
    cancel();
    loading.value = false;
    proxy.$modal.msgSuccess("分切复卷成功");
  });
}
function sureSubmit() {
  let obj = { ...form.value };
  obj = Object.assign(obj, previousClassInfo.value[0]);
  obj = Object.assign(obj, formSH.value);
  obj.recordTime = null;
  obj.auditTime = null;
  loading.value = true;
  emit("setActions", actions.value);
  if (parentType.value == "add") {
    addDoReportWork(obj)
      .then(() => {
        cancel();
        loading.value = false;
        proxy.$modal.msgSuccess("报工成功");
      })
      .catch(() => {
        loading.value = false;
      });
  }
  if (parentType.value == "audit") {
    auditReportWork(obj)
      .then(() => {
        cancel();
        loading.value = false;
        proxy.$modal.msgSuccess("审核成功");
      })
      .catch(() => {
        loading.value = false;
      });
  }
  if (parentType.value == "reapplyAdd") {
    againReportWork(obj)
      .then(() => {
        cancel();
        loading.value = false;
        proxy.$modal.msgSuccess("报工成功");
      })
      .catch(() => {
        loading.value = false;
      });
  }
}
getFactorys();
// 获取退料入仓信息
function getReturn(id) {
  getReturnMaterialsInfo(id).then((res) => {
    if (res && res.data) {
      returnMaterialsList.value = [res.data];
    }
  });
}
onMounted(() => {
  const { data } = attrs;
  parentType.value = data.parentType;
  editAble.value = true;
  status.value = data.status;
  getYBGList(data);
  if (parentType.value == "view" && status.value == "9") {
    getReturn(data.whStorehouseInId);
  }

  if (data?.id) {
    getDetail(data.id);
  } else {
    const today = new Date();
    const year = today.getFullYear();
    const month = today.getMonth() + 1; // JavaScript中月份从0开始
    const day = today.getDate();
    // 组合成YYYY-MM-DD格式
    const isoDate = `${year}-${month < 10 ? "0" + month : month}-${day < 10 ? "0" + day : day}`;
    form.value.prodDate = isoDate;
  }
  if (parentType.value == "view") {
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
    ];
    emit("setActions", actions.value);
  } else {
    actions.value = [
      {
        text: "取 消",
        theme: "",
        handle: () => {
          cancel();
        },
      },
      {
        text: "确 定",
        theme: "primary",
        handle: () => {
          submitForm();
        },
        loading: submitLoading.value,
      },
    ];
    emit("setActions", actions.value);
  }
});
</script>
<style lang="scss" scoped>
:deep(.el-table table tr th.start div::before) {
  color: red;
  content: "*";
}

.showDetail {
  width: 240px;
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.previousClasses {
  margin-bottom: 10px;
}
</style>
